import argparse
from datetime import date
# import doctest
import math
import os
import random
import re
import shutil
import glob
import sys
from timeit import Timer
import unittest
import zlib
# from urllib.request import urlopen


def stdlib():
    '''10. 标准库简介'''
    print('10. 标准库简介')
    _operating_system_interface()
    _file_wildcards()
    _command_line_arguments()
    _error_output_redirection_and_program_termination()
    _string_pattern_matching()
    _mathematics()
    _internet_access()
    _dates_and_times()
    _data_compression()
    _performance_measurement()
    _quality_control()
    _batteries_included()


def _operating_system_interface():
    print('10.1. 操作系统接口')
    print('get cwd:', os.getcwd())
    os.chdir('./tutorial/chapter10')
    print('change cwd:', os.getcwd())
    os.system('mkdir today')
    # dir(os)
    # help(os)
    shutil.copyfile('copy.txt', 'copy2.txt')
    # shutil.move('copy2.txt', 'today')
    os.chdir('../..')
    print('get cwd:', os.getcwd())


def _file_wildcards():
    print('10.2. 文件通配符')
    print('*.py:', glob.glob('*.py'))


def _command_line_arguments():
    print('10.3. 命令行参数')
    print('argv:', sys.argv)
    parser = argparse.ArgumentParser(
        description='分行显示每个文件')
    parser.add_argument('filenames', nargs='+')
    parser.add_argument('-l', '--lines', type=int, default=10)
    args = parser.parse_args()
    print(args)


def _error_output_redirection_and_program_termination():
    print('10.4. 错误输出重定向和程序终止')
    sys.stderr.write('Warning, log file not found starting a new one\n')


def _string_pattern_matching():
    print('10.5. 字符串模式匹配')
    print('findall:', re.findall(
        r'\bf[a-z]*', 'which foot or hand fell fastest'))
    print('sub:', re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat'))


def _mathematics():
    print('10.6. 数学')
    print('pi:', math.cos(math.pi / 4))
    print('log:', math.log(1024, 2))
    print('choice:', random.choice(['apple', 'pear', 'banana']))
    print('sample:', random.sample(range(100), 10))
    print('random:', random.random())
    print('randrange:', random.randrange(6))


def _internet_access():
    # with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') \
    #         as response:
    #     for line in response:
    #         line = line.decode()
    #         if line.startswith('datetime'):
    #             print(line.rstrip())
    pass


def _dates_and_times():
    print('10.8. 日期和时间')
    now = date.today()
    print('now:', now)
    format = now.strftime('%m-%d-%y. %d %b %Y is a %A on the %d day of %B.')
    print('custom format:', format)
    birthday = date(1964, 7, 31)
    age = now - birthday
    print('age days:', age.days)


def _data_compression():
    print('10.9. 数据压缩')
    s = b'witch which has which witches wrist watch'
    print('s length:', len(s))
    t = zlib.compress(s)
    print('t compress length:', len(t))
    print('s crc32:', zlib.crc32(s))


def _performance_measurement():
    print('10.10. 性能测量')
    t = Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
    print('timeit:', t)


def _quality_control():
    def average(values):
        '''Computes the arithmetic mean of a list of numbers.

        >>> print(average([20, 30, 70]))
        40.0
        '''
        return sum(values) / len(values)

    class TestStatisticalFunctions(unittest.TestCase):
        def test_average(self):
            self.assertEqual(average([20, 30, 70]), 40.0)
            self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
            with self.assertRaises(ZeroDivisionError):
                average([])
            with self.assertRaises(TypeError):
                average(20, 30, 70)  # type: ignore

    print('10.11. 质量控制')
    # doctest.testmod()
    # unittest.main()


def _batteries_included():
    print('10.12. 自带电池')
